package com.example.onlinetaxi.ui.activity.Driver.RegisterPage;

import android.content.Intent;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.AdapterView;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Spinner;
import android.widget.TextView;
import android.widget.Toast;

import com.example.onlinetaxi.R;
import com.example.onlinetaxi.dto.DataResponse;
import com.example.onlinetaxi.ui.activity.BaseActivity;
import com.example.onlinetaxi.ui.activity.HomePage.HomeActivity;
import com.example.onlinetaxi.util.OKHttpUtil.GetDataResponse;
import com.example.onlinetaxi.util.OKHttpUtil.HttpUrl;
import com.example.onlinetaxi.util.OKHttpUtil.OKHttpUtil;
import com.example.onlinetaxi.util.phoneUtil.PhoneUtil;
import com.example.onlinetaxi.view.VerifyCodeButton;

import java.util.HashMap;
import java.util.Map;
import java.util.regex.Pattern;

public class DriverRegisterActivity extends BaseActivity {
    // 下拉框组件
    Spinner brandSpinner;
    Spinner colorSpinner;
    // 输入框
    private EditText phoneET;
    private EditText verifyCodeET;
    private EditText passwordET;
    private EditText repasswordET;
    private EditText carNumberET;
    // 文本按钮
    private TextView backToPassengerBtn;
    // 按钮
    private Button registerButton;
    private VerifyCodeButton verifyCodeButton;

    // 用户输入
    private String phone;
    private String verifyCode;
    private String password;
    private String repassword;
    // 汽车品牌
    private String carBrand;
    // 汽车颜色
    private String carColor;
    // 汽车牌号
    private String carNumber;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_login);

        initView();

        initEvent();
    }

    private void initEvent() {
        // 注册按钮
        registerButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                // 对用户输入进行验证
                if (isCorrect()) {
                    // 通过验证
                    // 向后端发起注册请求
                    if (sendRegisterRequest()) {
                        // 提示用户注册成功
                        Toast.makeText(DriverRegisterActivity.this, "注册成功！", Toast.LENGTH_SHORT).show();
                        // 回到登录界面
                        Intent intent = new Intent(DriverRegisterActivity.this, HomeActivity.class);
                        startActivity(intent);
                        // 销毁当前界面
                        finish();
                    } else {
                        // 请求发起失败
                        Toast.makeText(DriverRegisterActivity.this, "注册请求失败，请联系管理员进行处理！", Toast.LENGTH_SHORT).show();
                    }
                }
            }
        });
        // 验证码发送按钮
        verifyCodeButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                // 获取手机号
                phone = phoneET.getText().toString();

                // 判断phone的值是否合适
                boolean isPhone = PhoneUtil.isMobileNO(phone);
                if (!isPhone) {
                    // 手机号错误
                    Toast.makeText(DriverRegisterActivity.this, "手机号格式错误！", Toast.LENGTH_SHORT).show();
                } else {
                    // 提示用户发送成功
                    Toast.makeText(DriverRegisterActivity.this, "短信验证码已发送！", Toast.LENGTH_SHORT).show();
                    // 设置验证码输入框获取焦点
                    verifyCodeET.setFocusable(true);
                    verifyCodeET.requestFocus();

                    // 按钮不可再点击
                    verifyCodeButton.start();

                    // 核心：设置向后台提交的参数
                    Map<String, String> map = new HashMap<>();
                    map.put("phone", phone);
                    // 发送post异步请求
                    String response = OKHttpUtil.postAsyncRequest(HttpUrl.getBaseUrl(), map, "SMS", "registerMessage");
                    // 接收响应体
                    DataResponse dataResponse = GetDataResponse.getDataResponse(response);
                    if (dataResponse.getCode().equals("200")) {
                        // 请求发送成功
                        Log.e("validate-code", dataResponse.getData().get("validate-code").toString());
                    } else {
                        Toast.makeText(DriverRegisterActivity.this, dataResponse.getData().get("error").toString(), Toast.LENGTH_SHORT).show();
                    }
                }
            }
        });

        // 消除当前界面
        backToPassengerBtn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                finish();
            }
        });

        // 品牌选择器
        brandSpinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
            @Override
            public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
                carBrand = parent.getItemAtPosition(position).toString();
            }

            @Override
            public void onNothingSelected(AdapterView<?> parent) {
                Toast.makeText(getApplicationContext(), "onNothingSelected", Toast.LENGTH_LONG).show();
            }
        });
        // 颜色选择器
        colorSpinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
            @Override
            public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
                carColor = parent.getItemAtPosition(position).toString();
            }

            @Override
            public void onNothingSelected(AdapterView<?> parent) {
                Toast.makeText(getApplicationContext(), "onNothingSelected", Toast.LENGTH_LONG).show();
            }
        });
    }

    private boolean sendRegisterRequest() {
        // 组织表单数据
        Map<String, String> map = new HashMap<>();
        map.put("phone", phone);
        map.put("password", password);
        map.put("verifyCode", verifyCode);
        // 用户类别十分重要
        map.put("type", "driver");
        map.put("carNumber", carNumber);
        map.put("carColor", carColor);
        map.put("carBrand", carBrand);

        // 向后端发起注册请求
        String response = OKHttpUtil.postAsyncRequest(HttpUrl.getBaseUrl(), map, "register", "doRegister");
        DataResponse dataResponse = GetDataResponse.getDataResponse(response);
        // 从返回数据中取出请求是否成功的参数
        if (dataResponse.getCode().equals("200")) {
            // 操作成功
            Toast.makeText(DriverRegisterActivity.this,
                    GetDataResponse.getDataResponse(response).getData().get("success").toString(),
                    Toast.LENGTH_SHORT).show();
        } else {
            //操作失败
            Toast.makeText(DriverRegisterActivity.this,
                    GetDataResponse.getDataResponse(response).getData().get("error").toString(),
                    Toast.LENGTH_SHORT).show();
        }

        return true;
    }

    private boolean isCorrect() {
        // 获取用户输入
        phone = phoneET.getText().toString();
        verifyCode = verifyCodeET.getText().toString();
        password = passwordET.getText().toString();
        repassword = repasswordET.getText().toString();
        // 车牌号
        carNumber = carNumberET.getText().toString();

        // 判断用户注册输入内容是否合理
        if (!PhoneUtil.isMobileNO(phone)) {
            Toast.makeText(DriverRegisterActivity.this, "手机号格式错误！", Toast.LENGTH_SHORT).show();
            return false;
        } else if (verifyCode.equals("") || verifyCode == null) {
            Toast.makeText(DriverRegisterActivity.this, "验证码不能为空！！", Toast.LENGTH_SHORT).show();
            return false;
        } else if (password.equals("") || password == null) {
            Toast.makeText(DriverRegisterActivity.this, "密码不能为空！", Toast.LENGTH_SHORT).show();
            return false;
        } else if (repassword.equals("") || repassword == null) {
            Toast.makeText(DriverRegisterActivity.this, "重复密码不能为空！", Toast.LENGTH_SHORT).show();
            return false;
        } else if (!password.equals(repassword)) {
            Toast.makeText(DriverRegisterActivity.this, "两次输入的密码不一致！", Toast.LENGTH_SHORT).show();
            return false;
        } else if (carColor.equals("请选择汽车颜色")) {
            Toast.makeText(DriverRegisterActivity.this, "请选择汽车颜色！", Toast.LENGTH_SHORT).show();
            return false;
        } else if (carBrand.equals("请选择汽车品牌")) {
            Toast.makeText(DriverRegisterActivity.this, "请选择汽车品牌！", Toast.LENGTH_SHORT).show();
            return false;
        } else if (carNumber == null || checkPlateNumberFormat(carNumber)) {
            Toast.makeText(DriverRegisterActivity.this, "您输入的汽车牌号格式不正确！", Toast.LENGTH_SHORT).show();
            return false;
        }

        return true;
    }

    public boolean checkPlateNumberFormat(String carNumber) {
        String pattern = "([京津沪渝冀豫云辽黑湘皖鲁新苏浙赣鄂桂甘晋蒙陕吉闽贵粤青藏川宁琼]{1}(([A-HJ-Z]{1}[A-HJ-NP-Z0-9]{5})|([A-HJ-Z]{1}(([DF]{1}[A-HJ-NP-Z0-9]{1}[0-9]{4})|([0-9]{5}[DF]{1})))|([A-HJ-Z]{1}[A-D0-9]{1}[0-9]{3}警)))|([0-9]{6}使)|((([沪粤川云桂鄂陕蒙藏黑辽渝]{1}A)|鲁B|闽D|蒙E|蒙H)[0-9]{4}领)|(WJ[京津沪渝冀豫云辽黑湘皖鲁新苏浙赣鄂桂甘晋蒙陕吉闽贵粤青藏川宁琼·•]{1}[0-9]{4}[TDSHBXJ0-9]{1})|([VKHBSLJNGCE]{1}[A-DJ-PR-TVY]{1}[0-9]{5})";
        return Pattern.matches(pattern, carNumber);
    }

    private void initView() {
        // 选择器
        brandSpinner = findViewById(R.id.driver_car_brand_spinner);
        colorSpinner = findViewById(R.id.driver_car_color_spinner);
        // 输入框
        phoneET = findViewById(R.id.driver_register_phone);
        verifyCodeET = findViewById(R.id.driver_register_verify_code);
        passwordET = findViewById(R.id.driver_register_password);
        repasswordET = findViewById(R.id.driver_register_repassword);
        carNumberET = findViewById(R.id.driver_register_car_number);
        backToPassengerBtn = findViewById(R.id.register_passenger);
        // 按钮
        registerButton = findViewById(R.id.driver_register_btn);
        verifyCodeButton = findViewById(R.id.driver_register_get_code);
    }
}